#include "dragview.h"
#include "treemodel.h"
#include <QWidget>
#include <QStyleOptionViewItem>
#include <QPainter>
#include <QPixmap>
#include <QDrag>
#include <QMimeData>
#include <QColor>
#include <QVector>
#include <QVariantMap>

DragView::DragView(QWidget *parent)
    : QTreeView(parent)
{
    setSelectionBehavior(QAbstractItemView::SelectRows);
    setDragEnabled(true);
    setAcceptDrops(true);
    setDropIndicatorShown(true);
    setDragDropMode(QAbstractItemView::InternalMove);
    setSelectionMode(QAbstractItemView::ExtendedSelection);

    setDragDropOverwriteMode(false);

    // 设置样式
    setStyleSheet("QTreeView {"
                  "   background-color: #F0F0F0;"
                  "   font: 10pt;"
                  "   alternate-background-color: #E8E8E8;"
                  "}"
                  "QHeaderView::section {"
                  "   background-color: #D3D3D3;"
                  "   padding: 4px;"
                  "   border: 1px solid #C0C0C0;"
                  "}");
    setAlternatingRowColors(true);
}

void DragView::setTreeModel(TreeModel *m)
{
    model = m;
    setModel(m);
    expandAll();
}

void DragView::startDrag(Qt::DropActions supportedActions)
{
    QModelIndexList indexes = selectedIndexes();
    if (indexes.isEmpty())
        return;

    QDrag *drag = new QDrag(this);
    QMimeData *mimeData = model->mimeData(indexes);
    drag->setMimeData(mimeData);

    // 创建拖拽预览图像
    QRect rect = visualRect(indexes.first());
    QPixmap pixmap(rect.width(), rect.height());
    pixmap.fill(Qt::transparent);

    QPainter painter(&pixmap);
    QStyleOptionViewItem option;
    option.initFrom(this);
    option.rect = QRect(0, 0, rect.width(), rect.height());

    // 绘制整行背景
    painter.fillRect(option.rect, option.palette.base());

    // 绘制每列内容
    for (int col = 0; col < model->columnCount(); ++col) {
        QModelIndex idx = model->index(indexes.first().row(), col, indexes.first().parent());
        option.rect.setWidth(columnWidth(col));
        itemDelegate()->paint(&painter, option, idx);
        option.rect.translate(columnWidth(col), 0);
    }

    painter.end();

    drag->setPixmap(pixmap);
    drag->setHotSpot(QPoint(pixmap.width()/2, pixmap.height()/2));

    drag->exec(supportedActions, Qt::MoveAction);
}
